package com.citsin.atlas.fragment

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.citsin.atlas.R
import com.citsin.atlas.adapter.AlbumAdapter
import com.citsin.atlas.viewmodel.AlbumViewModel
import kotlinx.android.synthetic.main.fragment_album.*


/**
 * citsin
 * 2019-06-04
 */
class AlbumFragment : Fragment() {

    private lateinit var mViewModel: AlbumViewModel
    private lateinit var mAdapter: AlbumAdapter

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mAdapter = AlbumAdapter(context)
        mViewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application).create(
            AlbumViewModel::class.java
        )
        mViewModel.getAlbums().observe(this, Observer { albums ->
            mAdapter.submitList(albums)
        })
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_album, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        recyclerView.addItemDecoration(DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL))
        recyclerView.adapter = mAdapter
        mAdapter.setOnItemClickListener { _, album ->
            album?.let {
                val bundle = arguments
                bundle!!.putString("id", album.id)
                Navigation.findNavController(view).navigate(R.id.action_album_to_media, bundle)
            }
        }
    }
}
